from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from libs.yuntongxun.sms import CCP

# APIView
# GenericAPIView
# ListAPIView,RetrieveAPIView
from verifications.serializers import RegisterSMSCodeSerializer


class RegisterImageCodeView(APIView):
    """
        生成验证码
        GET verifications/imagecodes/(?P<image_code_id>.+)/
        需要通过JS生成一个唯一码,以确保后台对图片进行校验
    """

    def get(self, request, image_code_id):
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % image_code_id, 60, text)
        print(text)
        return HttpResponse(image, content_type='image/jpeg')


class RegisterSMSCodeView(GenericAPIView):
    """
        获取短信验证码
        GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx&image_code_id=xxxx
        获取短信验证码,首先需要校验 验证码

        思路:
        创建序列化器,定义text 和 image_code_id
        redis 判断该用户是否频繁获取
        生成短信验证码
        redis增加记录
        发送短信
        返回响应
    """
    serializer_class = RegisterSMSCodeSerializer

    def get(self, requset, mobile):
        serializer = self.get_serializer(data=requset.query_params)
        serializer.is_valid(raise_exception=True)
        redis_conn = get_redis_connection('code')
        if redis_conn.get('sms_flag_%s' % mobile):
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)
        from random import randint
        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)
        redis_conn.setex('sms_%s' % mobile, 5 * 60, sms_code)
        redis_conn.setex('sms_flag_%s' % mobile, 60, 1)
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, 5], 1)
        from celery_tasks.sms.tasks import send_sms_code

        # 注意: 异步任务必须使用 delay调用
        # delay的参数是 和 任务的参数是一致的
        # send_sms_code(mobile,sms_code) --错误代码 不能这样发送
        send_sms_code.delay(mobile, sms_code)
        return Response({'message': 'ok'})
